const Koa = require('koa')
const Router = require('@koa/router')
// const cors = require('koa2-cors'); //跨域处理


const app = new Koa()
const router = new Router()
router.get('/', ctx => {
  ctx.body = 'hello'
})

router.get('/list', async ctx => {

  console.log('list开始了');
  await sleep(2000)
  console.log('list结束了');
  ctx.body = 'hello'
})

router.get('/sleep', async ctx => {
    let request = ctx.request;
    let {milliSeconds} = request.query;

    await sleep(milliSeconds)
    let code = '000000'
    if (milliSeconds > 3000) {
        code = 'e00001'
    }
    ctx.body = {milliSeconds, code}
})



async function sleep(milliSeconds) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, milliSeconds);
  })
}





app.use(router.routes()).use(router.allowedMethods());



/*app.use(
  cors({
    origin: function (ctx) { //设置允许来自指定域名请求
      if (ctx.url === '/test') {
        return '*'; // 允许来自所有域名请求
      }

      return '*'; // 允许来自所有域名请求
      // return 'http://localhost:8080'; //只允许http://localhost:8080这个域名的请求
    },
    maxAge: 5, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
  })
);*/


app.listen(3000, () => {
  console.log(3000);
})